package org.snackframework.util;

import org.springframework.asm.Label;
import org.springframework.asm.commons.EmptyVisitor;

public class LocalVariableTableVisitor extends EmptyVisitor
{
	private final ParameterNameDiscoveringVisitor memberVisitor;

	private final boolean isStatic;

	private String[] parameterNames;

	private boolean hasLvtInfo = false;

	public LocalVariableTableVisitor(ParameterNameDiscoveringVisitor memberVisitor, boolean isStatic) {
		this.memberVisitor = memberVisitor;
		this.isStatic = isStatic;
		this.parameterNames = new String[memberVisitor.numParamsExpected];
	}

	public void visitLocalVariable(
			String name, String description, String signature, Label start, Label end, int index) {
		this.hasLvtInfo = true;
		int[] lvtSlotIndices = this.memberVisitor.lvtSlotIndex;
		for (int i = 0; i < lvtSlotIndices.length; i++) {
			if (lvtSlotIndices[i] == index) {
				this.parameterNames[i] = name;
			}
		}
	}

	public void visitEnd() {
		if (this.hasLvtInfo || (this.isStatic && this.parameterNames.length == 0)) {
			 // visitLocalVariable will never be called for static no args methods
			 // which doesn't use any local variables.
			 // This means that hasLvtInfo could be false for that kind of methods
			 // even if the class has local variable info.
			this.memberVisitor.parameterNames = this.parameterNames;
		}
	}

}
